const model = require('../models/commentModel'),
  errCode = require('../../conf/errorCode'),
  wrap = require('../helper/wrap'),
  moment = require('moment'),
  conf = require('../../conf/const'),
  util = require('../helper/util'),
  _ = require('lodash'),
  {parseIntPageSize, checkContentValidate} = require('./commonService');

var getCommentByPostId = (exports.getCommentByPostId = function(
  postId,
  page,
  size,
  callback,
) {
  let errMsgs = null;
  [errMsgs, page, size] = parseIntPageSize(page, size);

  if (errMsgs == null) {
    var tmp = util.firstKeyOfNull(
      {
        postId,
      },
      ['postId'],
    );
    if (tmp != null) {
      return callback({
        errNo: errCode.LESS_OF_DATA_ERROR,
        extraMsgs: tmp,
      });
    }

    model.getCommentByPostId(postId, page, size, async (err, _rel) => {
      if (err) {
        return callback(err);
      }
      let commentList = _rel.list;
      for (let i = 0, len = commentList.length; i < len; i++) {
        commentList[i].createTime = util.formatTime(commentList[i].createTime);
      }
      _rel.list = commentList;
      return callback(null, _rel);
    });
  } else
    callback({
      errNo: errCode.INVALID_PARAM_ERROR,
      extraMsgs: errMsgs,
    });
});

exports.deleteCommentByIds = function(ids, callback) {
  if (_.isString(ids)) {
    ids = ids.trim().split(',');
    if (
      !_.every(ids, function(value) {
        return util.isIntegerLike(value);
      })
    ) {
      return callback({errNo: errCode.INVALID_FORMAT_ERROR, extraMsgs: 'ids'});
    }
  } else if (_.isNumber(ids)) {
    ids = [ids];
  } else if (
    !_.isArray(ids) ||
    !_.every(ids, function(value) {
      return util.isIntegerLike(value);
    })
  ) {
    return callback({errNo: errCode.INVALID_FORMAT_ERROR});
  }
  if (ids.length == 0) {
    return callback(null, {deleted: 0});
  }

  model.deleteCommentByIds(ids, (err, result) => {
    if (err) return callback(err);
    return callback(null, {
      deleted: result.changedRows,
    });
  });
};
